package com.cyzy.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.tea.TeaException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 营业执照识别
 */
@Component
public class AliyunOcrUtil {

    @Value("${aliyun.ocr.AccessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.ocr.AccessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.ocr.endpoint}")
    private String endpoint;

    /**
     * <b>description</b> :
     * <p>使用AK&amp;SK初始化账号Client</p>
     * @return Client
     *
     * @throws Exception
     */
    public com.aliyun.ocr_api20210707.Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(accessKeyId)
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/ocr-api
        config.endpoint = endpoint;
        return new com.aliyun.ocr_api20210707.Client(config);
    }
    public Map<String, Object> method(String imgPath) throws Exception {
        com.aliyun.ocr_api20210707.Client client = this.createClient();
        // 需要安装额外的依赖库，直接点击下载完整工程即可看到所有依赖。
        java.io.InputStream bodyStream = com.aliyun.darabonba.stream.Client.readFromFilePath(imgPath);
        com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseRequest recognizeBusinessLicenseRequest = new com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseRequest()
                .setBody(bodyStream);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

        try {
            com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseResponse resp =
                    client.recognizeBusinessLicenseWithOptions(recognizeBusinessLicenseRequest, runtime);



            JSONObject dataObj= JSON.parseObject(resp.body.data);

            System.out.println("-----------------------------");
            JSONObject data=dataObj.getJSONObject("data");
            System.out.println(data);

            //统一社会代码
            String creditCode=data.getString("creditCode");
            //名称
            String companyName=data.getString("companyName");
            //类型
            String companyType=data.getString("companyType");
            //公司地址
            String businessAddress=data.getString("businessAddress");
            //法定代表人
            String legalPerson=data.getString("legalPerson");
            //经营范围
            String businessScope=data.getString("businessScope");
            //注册资本
            String registeredCapital=data.getString("registeredCapital");
            //成立日期
            String RegistrationDate=data.getString("RegistrationDate");
            //营业期限
            String validPeriod=data.getString("validPeriod");
            //营业起始时间
            String validFromDate=data.getString("validFromDate");
            //营业截止时间
            String validToDate=data.getString("validToDate");
            //发证日期
            String issueDate=data.getString("issueDate");

            Map<String,Object> map=new HashMap<>();
            map.put("creditCode",creditCode);
            map.put("companyName",companyName);
            map.put("companyType",companyType);
            map.put("businessAddress",businessAddress);
            map.put("legalPerson",legalPerson);
            map.put("businessScope",businessScope);

            map.put("RegistrationDate",RegistrationDate);
            map.put("validPeriod",validPeriod);
            map.put("validFromDate",validFromDate);
            map.put("validToDate",validToDate);
            map.put("registeredCapital",registeredCapital);
            map.put("issueDate",issueDate);
            return map;

        } catch (TeaException error) {
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }

    /**
     * 身份证识别
     */
    public Map<String,Object> idNumber(String imgPath) throws Exception {
        com.aliyun.ocr_api20210707.Client client = this.createClient();
        // 需要安装额外的依赖库，直接点击下载完整工程即可看到所有依赖。
        java.io.InputStream bodyStream =
                com.aliyun.darabonba.stream.Client.readFromFilePath(imgPath);
        com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest recognizeIdcardRequest = new com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest()
                .setBody(bodyStream);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

        try {
            com.aliyun.ocr_api20210707.models.RecognizeIdcardResponse resp = client.recognizeIdcardWithOptions(recognizeIdcardRequest, runtime);
            com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(resp));
            if (resp.body != null && resp.body.data != null) {
                JSONObject dataObj = JSON.parseObject(resp.body.data);
                if (dataObj != null && dataObj.containsKey("data")) {
                    JSONObject dataSection = dataObj.getJSONObject("data");
                    if (dataSection != null && dataSection.containsKey("face")) {
                        JSONObject face = dataSection.getJSONObject("face");
                        if (face != null && face.containsKey("data")) {
                            JSONObject faceData = face.getJSONObject("data");
                            if (faceData != null) {
                                //姓名
                                String name = faceData.getString("name");
                                //性别
                                String sex = faceData.getString("sex");
                                //出生年月
                                String birthDate = faceData.getString("birthDate");
                                //民族
                                String ethnicity = faceData.getString("ethnicity");
                                //地址
                                String address = faceData.getString("address");
                                //身份证号码
                                String idNumber = faceData.getString("idNumber");

                                Map<String,Object> map=new HashMap<>();
                                map.put("name",name);
                                map.put("sex",sex);
                                map.put("birthDate",birthDate);
                                map.put("ethnicity",ethnicity);
                                map.put("address",address);
                                map.put("idNumber",idNumber);
                                return map;
                            }
                        }
                    }
                }
            }
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }

}
